package com.ita.acmsystem.merchant.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ita.acmsystem.merchant.entity.FoodTypes;
import com.ita.acmsystem.merchant.entity.Foods;
import com.ita.acmsystem.merchant.entity.Merchant;
import com.ita.acmsystem.merchant.entity.mock.ProtocalMock;
import com.ita.acmsystem.merchant.service.IFoodService;
import com.ita.acmsystem.merchant.service.IFoodTypesService;
import com.ita.acmsystem.merchant.service.IMerchantService;
import com.ita.acmsystem.merchant.service.impl.FoodServiceImpl;
import com.ita.acmsystem.merchant.service.impl.FoodTypesServiceImpl;
import com.ita.acmsystem.merchant.service.impl.MerchantServiceImpl;
import com.ita.acmsystem.merchant.util.SimpleJsonUtil;

/**
 * Servlet implementation class UpdateContentServlet
 */
public class AjaxUpdateFoodsContentServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private IFoodService foodService = new FoodServiceImpl();
	private IFoodTypesService foodTypesService = new FoodTypesServiceImpl();
	private IMerchantService merchantService = new MerchantServiceImpl();

	List<FoodTypes> foodTypesList;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AjaxUpdateFoodsContentServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		updateContent(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		updateContent(request, response);
	}

	private void updateContent(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String foodId = request.getParameter("foodId");
		
		System.out.println("AjaxUpdateFoodsContentServlet reveive update request, id=" + foodId);
		
		Foods food = foodService.getFoodsById(foodId);
		
		System.out.println("AjaxUpdateFoodsContentServlet: " + food);

		ProtocalMock protocal = null;
		if (food != null) {
			protocal = new ProtocalMock("success", "", food);
		} else {
			protocal = new ProtocalMock("error", "food is null", food);
		}

		response.setCharacterEncoding("utf-8");
		PrintWriter writer = response.getWriter();
		writer.write(SimpleJsonUtil.format(protocal));
		writer.close();
	}

}
